package com.system.boot.setting.service.impl;

import static com.system.common.constant.MessageConstant.CATALOGUE_CODE_EMPTY;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.api.SuperInterface;
import com.system.api.setting.entity.po.SysDictItem;
import com.system.boot.setting.mapper.DictItemMapper;
import com.system.boot.setting.service.DictItemService;
import com.system.common.enums.FactoryEnum;
import com.system.common.factory.CacheFactory;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.yang.common.core.exception.BaseException;
import org.yang.common.i18n.constant.I18nMessageConstant;
import org.yang.database.orm.entity.BaseQuery;
import org.yang.database.orm.entity.Options;

/**
 * @author: lslands
 * @version: 1.0
 * @create: 2024/5/18
 * @description:
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DictItemServiceImpl extends ServiceImpl<DictItemMapper, SysDictItem> implements DictItemService {

  private final CacheFactory cacheFactory;

  @Override
  public void isExists(String dictCode,String value) throws BaseException {
    boolean existsByCode = baseMapper.getExistsByCode(dictCode,value);
    if (existsByCode) {
      throw new BaseException(BaseException.REPEAT, value);
    }
  }


  @Override
  public int handInsert(SysDictItem record) throws BaseException {
    this.isExists(record.getDictCode(),record.getValue());
    if(record.getDefaulted()){
      LambdaUpdateWrapper<SysDictItem> wrapper = new LambdaUpdateWrapper<SysDictItem>()
              .set(SysDictItem::getDefaulted, false)
              .eq(SysDictItem::getDictCode, record.getDictCode());
      baseMapper.update(wrapper);
    }
    int result = baseMapper.insert(record);
    this.resetCache(result > 0);
    return 1;
  }

  @Override
  public int handUpdateById(SysDictItem record) throws BaseException {
    SysDictItem oldResult = Optional.ofNullable(baseMapper.selectById(record.getId()))
            .orElseThrow(() -> new BaseException(BaseException.NULL));
    if (!Objects.equals(record, oldResult)) {
      if (!record.getValue().equals(oldResult.getValue())) {
        this.isExists(record.getDictCode(),record.getValue());
      }
      if(record.getDefaulted() && !record.getDefaulted().equals(oldResult.getDefaulted())){
        LambdaUpdateWrapper<SysDictItem> wrapper = new LambdaUpdateWrapper<SysDictItem>()
                .set(SysDictItem::getDefaulted, false)
                .eq(SysDictItem::getDictCode, oldResult.getDictCode());
        baseMapper.update(wrapper);
      }
      int result = baseMapper.updateById(record);
      this.resetCache(result > 0);
      return result;
    }
    return 1;
  }

  @Override
  public int handEnabledById(Long id, Integer enabled, Integer revision) throws BaseException {
    SysDictItem oldResult =
        Optional.ofNullable(baseMapper.selectById(id))
            .orElseThrow(() -> new BaseException(BaseException.NULL));
    if (null == enabled) {
      throw new BaseException(I18nMessageConstant.VALIDATION_STATUS_EMPTY);
    }
    if (enabled.equals(oldResult.getEnabled())) {
      return 1;
    }
    int result = baseMapper.updateById(new SysDictItem(id, enabled, revision));
    this.resetCache(result > 0);
    return result;
  }


  @Override
  public int handDefautedById(Long id,boolean defaulted, Integer revision) throws BaseException {
    SysDictItem oldResult = Optional.ofNullable(baseMapper.selectById(id))
                    .orElseThrow(() -> new BaseException(BaseException.NULL));
    if(oldResult.getDefaulted()== defaulted){
      return 1;
    }
    if(defaulted){
      LambdaUpdateWrapper<SysDictItem> wrapper = new LambdaUpdateWrapper<SysDictItem>()
              .set(SysDictItem::getDefaulted, false)
              .eq(SysDictItem::getDictCode, oldResult.getDictCode());
      baseMapper.update(wrapper);
    }
    return baseMapper.updateById(new SysDictItem(id,defaulted,revision));
  }

  @Override
  public List<Options> getOptions(String dictCode) throws BaseException {
    List<SysDictItem> items = baseMapper.selectList(new LambdaQueryWrapper<SysDictItem>()
            .select(SysDictItem::getLabel, SysDictItem::getValue, SysDictItem::getType,SysDictItem::getScope)
            .eq(SysDictItem::getDictCode, dictCode));
    List<Options> options = CollectionUtil.emptyIfNull(items)
            .stream()
            .map(x -> {
              if(x.getScope().equals(1)){
                return new Options<>(Integer.parseInt(x.getValue()), x.getLabel(), x.getType());
              }
              return new Options<>(x.getValue(), x.getLabel(), x.getType());
            })
            .collect(Collectors.toList());
    return options;
  }

  @Override
  public Page<SysDictItem> getPage(BaseQuery query, String dictCode) throws BaseException{
    Page<SysDictItem> page = new Page<>(query.getCurrent(), query.getSize());
    if(StringUtils.isBlank(dictCode)) {
      throw new BaseException(CATALOGUE_CODE_EMPTY);
    }
    LambdaQueryWrapper<SysDictItem> wrapper = new LambdaQueryWrapper<SysDictItem>()
            .eq(SysDictItem::getDictCode, dictCode)
            .orderByDesc(SysDictItem::getValue);
    return baseMapper.selectPage(page, wrapper);
  }

  @Override
  public int deleteOne(Long id) throws BaseException {
    if( Objects.isNull(id)){
      throw new BaseException("id cannot be null");
    }
    int result = baseMapper.deleteById(id);
    this.resetCache(result>0);
    return result;
  }


  @Override
  public int deleteBatch(boolean delete, List<Long> ids) throws BaseException {
    int result = 0;
    if (!ids.isEmpty()) {
      result = delete ? baseMapper.deleteBatch(ids) : baseMapper.deleteBatchIds(ids);
      this.resetCache(result > 0);
    }
    return result;
  }

  @Override
  public void resetCache(boolean flag) {
    if (flag) {
      try {
        // 工厂方法
        cacheFactory.implementCacheProcessor(FactoryEnum.DICT.getType()).resetCache();
      } catch (BaseException e) {
        log.error("刷新字典缓存异常:{}", e.getMessage());
      }
    }
  }

}
